package spotifynews;

import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.*;

public class NOSHeadlinesPlayer extends Thread {

    private boolean stopNow = false;
    private boolean isPlaying = false;
    private boolean done = false;

    public NOSHeadlinesPlayer() {
        stopNow = false;
        done = false;
        isPlaying = false;
    }



    public void stopNews() {
        stopNow = true;
    }

    public boolean isStopping() {
        return stopNow;
    }

    public boolean isPlaying() {
        return isPlaying;
    }

    public boolean isDone() {
        return done;
    }

    public void run() {
            try {
                URL url = new URL("http://download.omroep.nl/nos/headlines/3FMNieuws/NOSHeadlines.mp3");

                AudioInputStream in = AudioSystem.getAudioInputStream(url);
                AudioInputStream din = null;
                AudioFormat baseFormat = in.getFormat();
                AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                        baseFormat.getSampleRate(),
                        16,
                        baseFormat.getChannels(),
                        baseFormat.getChannels() * 2,
                        baseFormat.getSampleRate(),
                        false);
                din = AudioSystem.getAudioInputStream(decodedFormat, in);
                // Play now.
                rawplay(decodedFormat, din);
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        
    }

    private void rawplay(AudioFormat targetFormat, AudioInputStream din) throws IOException, LineUnavailableException {
        isPlaying = true;

        byte[] data = new byte[4096];
        SourceDataLine line = getLine(targetFormat);
        if (line != null) {
            // Start
            line.start();
            int nBytesRead = 0, nBytesWritten = 0;
            while (nBytesRead != -1 && !stopNow) {
                nBytesRead = din.read(data, 0, data.length);
                if (nBytesRead != -1) {
                    nBytesWritten = line.write(data, 0, nBytesRead);
                }
            }
            // Stop
            line.drain();
            line.stop();
            line.close();
            din.close();
        }

        done = !stopNow;
        isPlaying = false;
    }

    private SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException {
        SourceDataLine res = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
        res = (SourceDataLine) AudioSystem.getLine(info);
        res.open(audioFormat);
        return res;
    }
}
